// 引入所需的图标工具
const icons = require('../../utils/icons.js');

Page({
    // 页面的初始数据
    data: {
        currentMonth: '', // 当前选择的月份
        totalExpense: 0, // 总支出
        remainingBudget: 0, // 剩余预算
        totalIncome: 0, // 总收入
        netAmount: 0, // 净额（收入-支出）
        records: [], // 记录列表
        showEditOverlay: false,
        editingRecord: null,
        expenseCategories: [
            { name: '餐饮', icon: 'eat' },
            { name: '购物', icon: 'shopping' },
            { name: '零食', icon: 'retail' },
            { name: '水果', icon: 'fruit' },
            { name: '交通', icon: 'transport' },
            { name: '修车', icon: 'car' },
            { name: '学习', icon: 'education' },
            { name: '礼物', icon: 'gift' },
            { name: '宠物', icon: 'pet' },
            { name: '游戏', icon: 'game' },
            { name: '话费', icon: 'phone' },
            { name: '水电', icon: 'lifefee' },
            { name: '运动', icon: 'sport' },
            { name: '仪容', icon: 'skin' },
            { name: '其他', icon: 'others' },
        ],
        incomeCategories: [
            { name: '生活费', icon: 'salary' },
            { name: '副业', icon: 'vicejob' },
            { name: '奖金', icon: 'bonus' },
            { name: '理财', icon: 'financing' },
            { name: '其他', icon: 'other' },
        ],
    },

    // 生命周期函数--监听页面加载
    onLoad: function() {
        const app = getApp();
        const currentMonth = `${app.globalData.currentYear}年${app.globalData.currentMonth}月`;
        this.setData({
            currentMonth: currentMonth,
            month: app.globalData.currentMonth,
            currentYear: app.globalData.currentYear
        });
        this.loadRecords();
    },

    // 生命周期函数--监听页面显示
    onShow: function() {
        const app = getApp();
        // 检查年月是否需要更新
        if (this.data.month !== app.globalData.currentMonth ||
            this.data.currentYear !== app.globalData.currentYear) {
            const currentMonth = `${app.globalData.currentYear}年${app.globalData.currentMonth}月`;
            this.setData({
                currentMonth: currentMonth,
                month: app.globalData.currentMonth,
                currentYear: app.globalData.currentYear
            });
        }
        // 无论如何都刷新记录
        this.loadRecords();
    },

    // 加载记录
    loadRecords: function() {
        const records = wx.getStorageSync('records') || [];

        // 使用当前选择的年份和月份
        const year = this.data.currentYear;
        const month = this.data.month - 1; // 月份需要减1，因为 Date 对象的月份是从0开始的

        // 过滤当前月份的记录
        const currentMonthRecords = records.filter(record => {
            const recordDate = new Date(record.date);
            return recordDate.getFullYear() === year &&
                recordDate.getMonth() === month;
        });

        // 处理记录数据
        const processedRecords = currentMonthRecords.map(record => ({
            ...record,
            amount: parseFloat(record.amount),
            displayAmount: Math.abs(parseFloat(record.amount)).toFixed(2),
        })).sort((a, b) => new Date(b.date) - new Date(a.date));

        // 计算当月总额
        let totalExpense = 0;
        let totalIncome = 0;
        currentMonthRecords.forEach(record => {
            if (record.amount < 0) {
                totalExpense += Math.abs(parseFloat(record.amount));
            } else {
                totalIncome += parseFloat(record.amount);
            }
        });
        const netAmount = totalIncome - totalExpense;

        this.setData({
            records: processedRecords,
            totalExpense: totalExpense.toFixed(2),
            totalIncome: totalIncome.toFixed(2),
            netAmount: netAmount.toFixed(2)
        });

        // 更新剩余预算
        const monthlyBudget = wx.getStorageSync('monthlyBudget') || 0;
        const remainingBudget = Math.max(0, monthlyBudget - totalExpense);
        this.setData({
            remainingBudget: remainingBudget.toFixed(2)
        });
    },

    // 切换月份
    changeMonth: function(e) {
        const app = getApp();
        const date = new Date(e.detail.value);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const currentMonth = `${year}年${month}月`;

        app.updateCurrentDate(year, month);
        this.setData({
            currentMonth: currentMonth,
            month: month,
            currentYear: year
        });
        this.loadRecords();
    },

    // 显示添加记录模态框
    showAddRecordModal: function() {
        wx.navigateTo({ url: '/packageA/pages/addRecord/addRecord' });
    },

    // 获取当月支出
    getCurrentMonthExpenses: function(records) {
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth() + 1;

        return records.reduce((total, record) => {
            const recordDate = new Date(record.date);
            if (recordDate.getFullYear() === currentYear && recordDate.getMonth() + 1 === currentMonth && record.amount < 0) {
                return total + Math.abs(record.amount);
            }
            return total;
        }, 0);
    },

    // 点击记录时打开编辑浮层
    editRecord: function(e) {
        const recordId = e.currentTarget.dataset.id;
        const record = this.data.records.find(r => r.id === recordId);
        if (record) {
            this.setData({
                showEditOverlay: true,
                editingRecord: {
                    ...record,
                    displayAmount: Math.abs(record.amount).toFixed(2)
                }
            });
        }
    },

    // 关闭编辑浮层
    closeEditOverlay: function() {
        this.setData({
            showEditOverlay: false,
            editingRecord: null
        });
    },

    // 阻止冒泡
    stopPropagation: function() {
        return;
    },

    // 选择类别
    selectCategory: function(e) {
        const category = e.currentTarget.dataset.category;
        this.setData({
            'editingRecord.category': category
        });
    },

    // 处理金额输入
    handleAmountInput: function(e) {
        let value = e.detail.value;
        value = value.replace(/[^\d.]/g, '');
        const parts = value.split('.');
        if (parts.length > 2) {
            value = parts[0] + '.' + parts.slice(1).join('');
        }
        if (parts.length === 2 && parts[1].length > 2) {
            value = parts[0] + '.' + parts[1].substring(0, 2);
        }
        this.setData({
            'editingRecord.displayAmount': value
        });
    },

    // 处理备注输入
    handleRemarkInput: function(e) {
        this.setData({
            'editingRecord.remark': e.detail.value
        });
    },

    // 更新记录
    updateRecord: function() {
        const { editingRecord } = this.data;
        const numAmount = parseFloat(editingRecord.displayAmount);

        if (isNaN(numAmount) || numAmount <= 0) {
            wx.showToast({
                title: '请输入有效金额',
                icon: 'none'
            });
            return;
        }

        // 获取所有记录
        const records = wx.getStorageSync('records') || [];
        const index = records.findIndex(r => r.id === editingRecord.id);

        if (index !== -1) {
            // 保持原来的正负号
            const isExpense = records[index].amount < 0;
            records[index] = {
                ...editingRecord,
                amount: isExpense ? -numAmount : numAmount
            };

            // 保存更新后的记录
            wx.setStorageSync('records', records);

            // 刷新页面数据
            this.loadRecords();

            // 关闭浮层
            this.closeEditOverlay();

            wx.showToast({
                title: '更新成功',
                icon: 'success'
            });
        }
    },

    // 删除记录
    deleteRecord: function() {
        wx.showModal({
            title: '确认删除',
            content: '确定要删除这条记录吗？',
            success: res => {
                if (res.confirm) {
                    const records = wx.getStorageSync('records') || [];
                    const newRecords = records.filter(r => r.id !== this.data.editingRecord.id);
                    wx.setStorageSync('records', newRecords);
                    this.loadRecords();
                    this.closeEditOverlay();
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    });
                }
            }
        });
    }
});